#include "MDL_Button.h"
#include "DDL/DDL_Button/DDL_Button.h"
// 初始化按键
void MDL_Button_Init(Button* btn, unsigned int pin) {
    btn->pin = pin;
    DDL_Button_Init(pin);  // 初始化底层硬件
    btn->state = BUTTON_RELEASED;
    btn->lastState = BUTTON_RELEASED;
    btn->pressTime = 0;
    btn->releaseTime = 0;
    btn->lastReleaseTime = 0;
    btn->clickCount = 0;
    btn->isPressed = 0;
    btn->event = BUTTON_EVENT_NONE;
}

// 更新按键状态（需要定期调用）
void MDL_Button_Update(Button* btn, unsigned int currentTime) {
    // 读取按键当前状态（调用驱动层函数）
   unsigned int currentState = DDL_Button_Read(btn->pin) ? BUTTON_PRESSED : BUTTON_RELEASED;
    
    // 状态更新
    btn->lastState = btn->state;
    btn->state = currentState;
    
    // 检测按下事件
    if (btn->lastState == BUTTON_RELEASED && btn->state == BUTTON_PRESSED) {
        btn->pressTime = currentTime;
        btn->isPressed = 1;
    }
    // 检测释放事件
    else if (btn->lastState == BUTTON_PRESSED && btn->state == BUTTON_RELEASED) {
        btn->releaseTime = currentTime;
        btn->isPressed = 0;
        
        // 检查是否为有效按下（消抖）
        if ((btn->releaseTime - btn->pressTime) >= BUTTON_DEBOUNCE_TIME) {
            // 计算与上次释放的时间间隔，判断是否为连续点击
            unsigned int interval = btn->releaseTime - btn->lastReleaseTime;
            
            if (interval <= BUTTON_MULTI_CLICK_TIME) {
                btn->clickCount++;
            } else {
                btn->clickCount = 1;
            }
            
            btn->lastReleaseTime = btn->releaseTime;
        }
    }
    
    // 清除旧事件
    if (btn->event != BUTTON_EVENT_NONE) {
        return;
    }
    
    // 判断按键事件类型
    if (btn->isPressed) {
        // 判断是否长按
        if ((currentTime - btn->pressTime) >= BUTTON_LONG_PRESS_TIME) {
            btn->event = BUTTON_EVENT_LONG_PRESS;
        }
    } else {
        // 判断点击类型
        if (btn->clickCount > 0) {
            // 等待一段时间确认点击次数
            if ((currentTime - btn->lastReleaseTime) > BUTTON_MULTI_CLICK_TIME) {
                if (btn->clickCount == 1) {
                    btn->event = BUTTON_EVENT_CLICK;
                } else if (btn->clickCount == 2) {
                    btn->event = BUTTON_EVENT_DOUBLE_CLICK;
                } else if (btn->clickCount >= 3 && btn->clickCount <= BUTTON_MAX_MULTI_CLICK) {
                    btn->event = BUTTON_EVENT_MULTI_CLICK;
                }
                btn->clickCount = 0;
            }
        }
    }
}

// 获取按键事件
int MDL_Button_Get_Event(Button* btn) {
    return btn->event;
}

// 清除按键事件
void MDL_Button_Clear_Event(Button* btn) {
    btn->event = BUTTON_EVENT_NONE;
}